from typing import Union, List
from fastapi import FastAPI,Query
from pydantic import Required

app = FastAPI()

'''
3.1 Query 使用
'''
@app.get("/items1/")
async def read_items(q: Union[str, None] = Query(description="items1 interface")):
    query_items = {"q": q}
    return query_items


'''
3.2 通过 Query 校验
'''
#default—默认值
@app.get("/items21/")
async def read_items(q: Union[str, None] = Query(default=None)):
    query_items = {"q": q}
    return query_items

@app.get("/items22/")
async def read_items(q: str = Query(default="fixedquery")):
    query_items = {"q": q}
    return query_items


#max_length/min_length—字符最大/小长度
@app.get("/items3/")
async def read_items(q: Union[str, None] = Query(default=None, max_length=50, min_length=3)):
    query_items = {"q": q}
    return query_items


#添加正则表达式
@app.get("/items4/")
async def read_items(
    q: Union[str, None] = Query(default=None, regex="^fixedquery$")
):
    query_items = {"q": q}
    return query_items

#声明必需参数
'''声明为必需参数,当你在使用 Query 且需要声明一个值是必需的时，只需不声明默认参数：'''
@app.get("/items5/")
async def read_items(q: str = Query(min_length=3)):
    query_items = {"q": q}
    return query_items

'''使用省略号(...)声明必需参数'''
@app.get("/items6/")
async def read_items(q: str = Query(default=..., min_length=3)):
    query_items = {"q": q}
    return query_items

'''使用Pydantic中的Required代替省略号(...)'''
@app.get("/items7/")
async def read_items(q: str = Query(default=Required, min_length=3)):
    query_items = {"q": q}
    return query_items

'''声明更多元数据'''
@app.get("/items8/")
async def read_items(
    q: Union[str, None] = Query(
        default=None,
        title="Query string",
        description="Query string for the items to search in the database that have a good match",
        alias="item-query", #别名
        deprecated=True
    )
):
    query_items = {"q": q}
    return query_items

'''
3.3 查询参数设定为列表/多个值
'''
'''查询参数列表 / 多个值'''
@app.get("/items9/")
async def read_items(q: Union[List[str], None] = Query(default=None)):
    query_items = {"q": q}
    return query_items

'''具有默认值的查询参数列表 / 多个值'''
@app.get("/items10/")
async def read_items(q: List[str] = Query(default=["foo", "bar"])):
    query_items = {"q": q}
    return query_items


'''使用 list，List[int] 将检查（并记录到文档）列表的内容必须是整数。但是单独的 list 不会。'''
@app.get("/items11/")
async def read_items(q: list = Query(default=[])):
    query_items = {"q": q}
    return query_items


if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)